﻿using MySql.Data.MySqlClient;
using SuperJoe.Framework.Core.Exceptions;
using SuperJoe.Framework.UnitOfWorkSql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WWX.MemberPortal.DAL
{
    public abstract class BaseDAL
    {
        protected IUnitOfWork uow = null;

        public BaseDAL(IUnitOfWork uow)
        {
            this.uow = uow;
            
        }

        protected bool Execute(string sql, IDictionary<string, object> parameters = null)
        {
            return uow.ExecuteCommand(new List<SqlEntryCommand> { new SqlEntryCommand(sql, parameters) }) > 0;
        }

        protected bool Execute(params SqlEntryCommand[] sqlEntryCommands)
        {
            return uow.ExecuteCommand(sqlEntryCommands) > 0;
        }

        protected bool Execute(IEnumerable<SqlEntryCommand> sqlEntiryCommands)
        {
            return uow.ExecuteCommand(sqlEntiryCommands) > 0;
        }

        protected bool Execute(params DataTable[] datatables)
        {
            return uow.ExecuteCommand(datatables.Select(n => new DataTableCommand() { Table = n })) > 0;
        }

        protected int GetCount(string sql, IDictionary<string, object> parameters = null)
        {
            var result = uow.ExecuteScalar(sql, parameters);
            return Convert.ToInt32(result);
        }

        protected List<T> GetModels<T>(string sql, IDictionary<string, object> parameters = null) where T : new()
        {
            return uow.ExecuteDataSet(sql, parameters).Tables[0].ToEntities<T>().ToList();
        }

        protected DataTable GetDataTable(string sql, IDictionary<string, object> parameters = null)
        {
            return uow.ExecuteDataSet(sql, parameters).Tables[0];
        }

        protected T GetModel<T>(string sql, IDictionary<string, object> parameters = null) where T : new()
        {
            var rows = uow.ExecuteDataSet(sql, parameters).Tables[0].ToEntities<T>().ToList();
            if (rows.Count > 1)
            {
                throw new SuperJoeException("返回数据行数大于1");
            }

            if (rows.Count == 0)
            {
                return default(T);
            }

            return rows[0];
        }

        protected Dictionary<string, object> CreateParameters()
        {
            return new Dictionary<string, object>();
        }

        private static MySqlParameter[] ConvertToSqlParameters(IDictionary<string, object> parameters)
        {
            return parameters == null ? null : parameters.Select(n => new MySqlParameter("?" + n.Key, n.Value)).ToArray();
        }
    }
}
